/*
 * @filename AuthenticationSuccessHandler.java
 * 
 * @author barry
 * 
 * @version 0.0.1
 * 
 * @date 2020年1月14日
 */
package com.bnzj.core.webflux.security;

import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.util.JsonUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Base64;

/**
 * @author barry
 * @date 2020-01-14
 */
public class AuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {
    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        // 设置headers
        HttpHeaders httpHeaders = response.getHeaders();
        httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
        httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
        // 设置body
        byte[] dataBytes = {};
        try {
            User user = (User)authentication.getPrincipal();
            byte[] authorization = (user.getUsername() + ":" + user.getPassword()).getBytes();
            String token = Base64.getEncoder().encodeToString(authorization);
            httpHeaders.add(HttpHeaders.AUTHORIZATION, token);
            ResponseResult<UserDetails> result = ResponseResult.success();
            result.setData(user);
            dataBytes = JsonUtils.objToJson(result).getBytes();
        } catch (Exception e) {
            ResponseResult<String> result = ResponseResult.failure(ResultCode.FAILURE, e.getMessage());
            dataBytes = JsonUtils.objToJson(result).getBytes();
        }
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
        response.writeWith(Mono.just(bodyDataBuffer));
        return webFilterExchange.getChain().filter(exchange);
    }
}
